import random

from django.db import models

# Create your models here.
from django.db.models.signals import post_save, pre_delete, pre_save
from django.dispatch import receiver

from network.models import Person as NeoPerson


# from .serializers import PersonSerializer

class Status(models.Choices):
    # CHOICES选项 health
    HEALTH = '1', '健康'
    SUSPECTED = '2', '疑似'  # suspected
    INDCTION = '3', '感染'  # infection


class Gender(models.Choices):
    FEMALE = '0', '女'
    MALE = '1', '男'
    UNKONW = '2', '未知'


IMG_URL = 'http://121.196.107.223:8000/img/'


class Person(models.Model):
    STATUS_CHOICES = [
        ('1', '健康'),
        ('2', '密切接触'),
        ('3', '感染'),
    ]

    GENDER_CHOICES = [
        ('0', '女'),
        ('1', '男'),
        ('2', '未知'),
    ]

    card_id = models.CharField(help_text='卡号', verbose_name='卡号', max_length=30, unique=True)
    name = models.CharField(help_text='姓名', verbose_name='姓名', max_length=10, )
    # graphql
    permanent_residence = models.CharField(help_text='常驻地', verbose_name='常驻地', max_length=30)
    mobile = models.CharField(help_text='电话号码', verbose_name='电话', max_length=11, unique=True, db_index=True, )
    gender = models.CharField(help_text='性别', verbose_name='性别', choices=GENDER_CHOICES, default=2, max_length=1)
    age = models.IntegerField(help_text='年龄', verbose_name='年龄')
    is_vaccine = models.BooleanField(verbose_name='是否接种疫苗', default=False)

    status = models.CharField(help_text='状态', verbose_name='状态', default='1', choices=STATUS_CHOICES, max_length=1)
    image = models.CharField(help_text='头像', verbose_name='头像', default=IMG_URL + str(random.randint(1, 130)) + '.jpeg',
                             max_length=110)

    def __str__(self):
        return self.name

    # META类选项
    class Meta:
        verbose_name = '用户'
        verbose_name_plural = '全部用户'
        # ordering = ['-location_id']

    @property
    def serialize(self):
        person_info = {
            'node_id': self.id,  # 之后根据这个id去neo4j里面创建节点
            'name': self.name,
            'card_id': self.card_id,
            'permanent_residence': self.permanent_residence,
            'mobile': self.mobile,
            'gender': self.gender,
            'age': self.age,
            'is_vaccine': self.is_vaccine,
            'status': self.status,
            'image': self.image,
        }
        return person_info

    def to_neo4j(self):
        person_info = self.serialize
        person_node = NeoPerson(**person_info).save()
        if not person_node:
            raise ValueError(f'neo4j创建失败')
        return person_node.serialize


@receiver(pre_save, sender=Person)
def create_person_node(sender, instance, **kwargs):
    """
    创建一个person节点
    :param sender:
    :param instance:
    :param created:
    :param kwargs:
    :return:
    """
    # if created:
    print('创建之前没有id,')
    # node_info = instance.to_neo4j()
    # return node_info


@receiver(post_save, sender=Person)
def create_person_node(sender, instance, created, update_fields, raw, using, **kwargs):
    """
    创建一个person节点
    如果这个没执行成功，其实mysql也不会保存
    :param sender:
    :param instance:
    :param created:
    :param kwargs:
    :return:
    """
    if created:
        node_info = instance.to_neo4j()
        print(f'neo4j创建了{node_info}')
        return node_info


@receiver(post_save, sender=Person)
def update_person_node(sender, instance, created, **kwargs):
    #
    # todo 去neo4j里跟着更新
    if created:
        return
    person_info = instance.serialize
    person_node = NeoPerson.nodes.get_or_none(node_id=instance.id)
    if person_node:
        person_node.update(**person_info)
        print(f"neo4j中更新了{Person.serialize}")
        return Person.serialize
    raise ValueError(f'neo4j中没有节点id为{instance.id}')


@receiver(pre_delete, sender=Person)
def delete_person(sender, instance, **kwargs):
    # 如果这里没执行成果那边也不会执行
    # todo 去neo4j里跟着更新
    node_id = instance.id

    person_node = NeoPerson.nodes.get_or_none(node_id=node_id)
    if person_node:
        data = person_node.serialize
        person_node.delete()
        print(f'成功删除{instance.name}')
        return data
    raise ValueError(f'neo4j中没有节点id为{instance.id}')

